Skip to content

Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING#23543

Merged
wing328 merged 29 commits intoOpenAPITools:masterfrom
jpfinne:feature/normalizer_REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING
Apr 28, 2026
Merged

Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING#23543
wing328 merged 29 commits intoOpenAPITools:masterfrom
jpfinne:feature/normalizer_REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING

Conversation

@jpfinne
Copy link
Copy Markdown
Contributor

@jpfinne jpfinne commented Apr 14, 2026

fixes #19261, #912, #23527, #22013, #23276, #14769, #16391, #19194, #19261, #23577, #22209 (and probably others) when using the new REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalizer option.

The goal is to use inheritance with base classes when composition or useOneOfInterfaces don't work.
For example:

  • oneOf + discriminator mapping generates classes implementing and extending a base class
  • oneOf + discriminator generates an interface or use composition
  • discriminator name using a unique enum value

The normalizer converts oneOf with discriminators.
It ensures that:

  • discriminator mappings are created (using x-discriminator-value if present or single enum value).
  • It removes the oneOf.
  • It ensures that the referenced children correctly has an allOf to the parent.
  • it removes the single enum value in the referenced mappings if already present in the parent.

For the java generators, it means that inheritance with a base class class is generated instead of an interface.

Edge cases don't do anything:

  • no discriminator property
  • oneOf with inline schema
  • non matching number of oneOf nodes and number of discriminator mappings (if present)

Warning: the normalizer does not support inline oneOf (as seen in #23276 and in #15 using composed-oneof.yaml). A warning is outputted Inline oneOf schema not supported by REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING normalization. No transformation is done.
It might be nice to refactor the inline oneOfs in the OpenAPINormalizer, similar to REFACTOR_ALLOF_INLINE_SCHEMAS done in the InlineModelResolver.
ps: it can't be done in InlineModelResolver because it runs after the normalizer.

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @martin-mfg (2023/08)
| @cachescrubber (2022/02) @welshm (2022/02) @MelleD (2022/02) @atextor (2022/02) @manedev79 (2022/02) @javisst (2022/02) @borsch (2022/02) @banlevente (2022/02) @Zomzog (2022/09) @martin-mfg (2023/08)
@wing328

Please review


Summary by cubic

Adds a normalizer that replaces oneOf with discriminator.mapping and attaches allOf inheritance so Java and spring generators emit correct Jackson polymorphism and class hierarchies. Also refines composed/inline model handling and updates docs.

  • New Features

    • REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING=true: build discriminator.mapping from oneOf $refs (merge existing), remove oneOf, add an allOf parent $ref to each child, and move child properties under that allOf.
    • Remove the discriminator property from children when the base defines it; skip inline or non-$ref oneOf with a warning.
    • Discriminator value resolution: x-discriminator-value > single enum on the discriminator property (resolving $ref) > schema name.
    • Ensure inheritance for existing discriminator mappings by adding missing allOf links to children; do not duplicate links.
    • Docs: added CLI example for spring.
  • Bug Fixes

    • Use isParentReferencedInChild to avoid duplicate allOf links and recursion; fix allOf construction and discriminator property lookup via ModelUtils.getReferencedSchema.
    • Warnings for missing discriminator property, mapping/oneOf size mismatch, and unsupported inline cases.
    • After moving child properties into allOf, clear leftover child metadata to prevent duplication; convert empty ComposedSchema to plain Schema.
    • InlineModelResolver now gathers inline models for composed schemas with properties (fixes 22209).

Written for commit 0efdfbd. Summary will update on new commits.

@winklerm
Copy link
Copy Markdown

Thanks a lot for this quick fix!

I have verified it resolves the issue for our use-case.

@winklerm winklerm mentioned this pull request Apr 15, 2026
6 tasks
@jpfinne
Copy link
Copy Markdown
Contributor Author

jpfinne commented Apr 15, 2026

Thanks a lot for this quick fix!

I have verified it resolves the issue for our use-case.

This bug has bother me for months. I've initially tried to fix it in DefaultCodeGen, but the handling of composition vs inheritance is very complex.

I'll work on the PR. In the meantime you can create a custom normalizer:

NORMALIZER_CLASS: Set to full classname of a class extending the default org.openapitools.codegen.OpenAPINormalizer. It allows customization of the default normalizer

@jpfinne jpfinne changed the title normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING Improve OneOf handling with new normalizer REPLACE_ONE_OF_BY_DISCRIMINATOR_MAPPING Apr 17, 2026
@jpfinne jpfinne marked this pull request as ready for review April 18, 2026 16:16
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 18 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/customization.md">

<violation number="1" location="docs/customization.md:654">
P3: Malformed Markdown adds a stray backtick to the documented normalizer name, making the docs show/copy the option incorrectly.</violation>
</file>

<file name="pom.xml">

<violation number="1" location="pom.xml:27">
P1: Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.</violation>
</file>

<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1608">
P2: `schema.getOneOf()` is iterated without a null guard after `processSimplifyOneOf()` can clear `oneOf`, causing a potential NPE in discriminator replacement.</violation>

<violation number="2" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1619">
P1: Unconditionally removing `oneOf` can drop subtype metadata when the discriminator mapping is partial or not rebuilt.</violation>

<violation number="3" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1630">
P2: `hasParent()` returns false immediately when it encounters a visited `allOf` branch, so later siblings are never checked and an existing parent ref can be added again.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread pom.xml
@@ -23,6 +23,15 @@
<developerConnection>scm:git:git@github.com:openapitools/openapi-generator.git</developerConnection>
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Apr 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At pom.xml, line 27:

<comment>Root-level module declarations duplicate modules already listed in the default-active openapi-generator profile, which can make Maven fail with duplicated reactor projects.</comment>

<file context>
@@ -23,6 +23,15 @@
         <url>https://github.com/openapitools/openapi-generator</url>
     </scm>
+    <modules>
+        <module>modules/openapi-generator-core</module>
+        <module>modules/openapi-generator</module>
+        <module>modules/openapi-generator-cli</module>
</file context>
Fix with Cubic

Comment thread docs/customization.md Outdated
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1780">
P1: Regression in `hasParent()`: the new visited check short-circuits recursive traversal, so existing parent refs nested under `allOf` are missed and duplicate parent inheritance refs can be added.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@jpfinne jpfinne marked this pull request as draft April 19, 2026 19:35
@jpfinne jpfinne marked this pull request as ready for review April 20, 2026 08:30
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 18 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:649">
P2: `ensureInheritanceForDiscriminatorMappings()` is invoked on the pre-normalization schema instance, so any normalization path that returns a new Schema object makes the discriminator mapping changes apply to a discarded object.</violation>

<violation number="2" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1776">
P1: Moving `properties` into a nested `allOf` schema without moving `additionalProperties` changes validation semantics and can reject properties that should be allowed.</violation>
</file>

<file name="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/JavaFileAssert.java">

<violation number="1" location="modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/JavaFileAssert.java:62">
P2: `extendsClass(...)` does not verify the declaration is a class, so an interface with matching extended types can satisfy the assertion and hide a generator regression.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java:1758">
P2: Renaming this protected helper is a breaking API change for subclasses; downstream overrides of the old method name will no longer apply.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

-> avoid side effects with bugs in InlineModelResolver
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java">

<violation number="1" location="modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java:2297">
P2: `shallowCopy` is lossy despite claiming full field copy; it duplicates `setUnevaluatedItems` and omits other schema fields, risking metadata/constraint loss during schema normalization.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 3 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java">

<violation number="1">
P1: Returning simplified schemas without converting empty `ComposedSchema` to plain `Schema` can misclassify them as composed and alter downstream generation paths.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@@ -78,6 +78,10 @@ public class OpenAPINormalizer {
// are removed as most generators cannot handle such case at the moment
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Apr 25, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Returning simplified schemas without converting empty ComposedSchema to plain Schema can misclassify them as composed and alter downstream generation paths.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java, line 1094:

<comment>Returning simplified schemas without converting empty `ComposedSchema` to plain `Schema` can misclassify them as composed and alter downstream generation paths.</comment>

<file context>
@@ -1083,15 +1083,15 @@ protected Schema normalizeOneOf(Schema schema, Set<Schema> visitedSchemas) {
         schema = processSimplifyAnyOfEnum(schema);
         if (schema.getAnyOf() == null) {
-            return decomposeSchema(schema);
+            return schema;
         }
 
</file context>
Suggested change
// are removed as most generators cannot handle such case at the moment
+ if (schema instanceof ComposedSchema && schema.getOneOf() == null && schema.getAnyOf() == null && schema.getAllOf() == null) {
+ return ModelUtils.shallowCopy(schema, new Schema<>());
+ }
+ return schema;
Fix with Cubic

@cubic-dev-ai
Copy link
Copy Markdown
Contributor

cubic-dev-ai Bot commented Apr 25, 2026

You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment @cubic-dev-ai review.

@jpfinne
Copy link
Copy Markdown
Contributor Author

jpfinne commented Apr 25, 2026

@cubic-dev-ai review

@cubic-dev-ai
Copy link
Copy Markdown
Contributor

cubic-dev-ai Bot commented Apr 25, 2026

@cubic-dev-ai review

@jpfinne I have started the AI code review. It will take a few minutes to complete.

Comment thread docs/customization.md
@wing328
Copy link
Copy Markdown
Member

wing328 commented Apr 28, 2026

did some tests and the change looks good to me

diff --git a/api/openapi.yaml b/api/openapi.yaml
index 6f27abd..146c61c 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -9,10 +9,10 @@ components:
   schemas:
     GeoJsonObject:
       discriminator:
+        mapping:
+          MultiPolygon: "#/components/schemas/Multi-Polygon"
+          Polygon: "#/components/schemas/Polygon"
         propertyName: type
-      oneOf:
-      - $ref: "#/components/schemas/Polygon"
-      - $ref: "#/components/schemas/Multi-Polygon"
       properties:
         type:
           type: string

i'll update the doc after merging this PR

@wing328 wing328 merged commit 0b1ac88 into OpenAPITools:master Apr 28, 2026
15 checks passed
@wing328 wing328 added Enhancement: Feature OpenAPI Normalizer Normalize the spec for easier processing labels Apr 28, 2026
@wing328 wing328 added this to the 7.22.0 milestone Apr 28, 2026
@wing328 wing328 added Issue: Bug Inline Schema Handling Schema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf labels Apr 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Enhancement: Feature Inline Schema Handling Schema contains a complex schema in items/additionalProperties/allOf/oneOf/anyOf Issue: Bug OpenAPI Normalizer Normalize the spec for easier processing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][DefaultCodegen] OneOf with discriminator for referenced object with allOf

3 participants